package com.king.reentrantlock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author taomk
 * @version 1.0
 * @since 15-2-12 下午10:53
 */
public class ReentrantLockThread extends Thread {

	private static final Lock lock = new ReentrantLock();

	public ReentrantLockThread(String name) {
		super(name);
	}

	@Override
	public void run() {
		try {
			while (true) {
				// 在给定时间内尝试获得锁
				if (lock.tryLock(500, TimeUnit.MILLISECONDS)) {
					// if (lock.tryLock()) 尝试获得锁，如果成功，返回true，失败返回false。该方法不等待，立即返回。
					// lock.lock(); 获得锁，如果锁已经被占用，则等待。
					// lock.lockInterruptibly(); 获得锁，但优先响应中断。
					try {
						System.out.println("locked " + Thread.currentThread().getName());
						Thread.sleep(1000);
					} finally {
						lock.unlock();
						System.out.println("unlocked " + Thread.currentThread().getName());
					}
					break;
				} else {
					System.out.println("unable to lock " + Thread.currentThread().getName());
				}
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
			System.out.println(Thread.currentThread().getName() + " is Interrupted");
		}
	}
}
